package com.song.service;

import com.song.domain.Material;
import com.song.mapper.MaterialMapper;
import com.song.mapper.OrderItemMapper;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;

@Service
public class MaterialService {
    private final MaterialMapper mapper;
    private final OrderItemMapper orderItemMapper;

    public MaterialService(MaterialMapper mapper, OrderItemMapper orderItemMapper) {
        this.mapper = mapper;
        this.orderItemMapper = orderItemMapper;
    }

    public Material get(Long id) {
        return mapper.selectById(id);
    }

    public List<Material> list(int page, int size, String category) {
        int offset = Math.max(page - 1, 0) * size;
        return mapper.list(offset, size, category);
    }

    public int count(String category) {
        return mapper.count(category);
    }

    public Material create(Material material) {
        mapper.insert(material);
        return material;
    }

    public Material update(Material material) {
        mapper.update(material);
        return material;
    }

    public void delete(Long id) {
        if (id == null) return;
        int refs = orderItemMapper.countByMaterialId(id);
        if (refs > 0) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "该建材已被订单引用，无法删除");
        }
        mapper.delete(id);
    }
}